<!-- 心理测评管理 -->

<template>
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>心理测评</el-breadcrumb-item>
      <el-breadcrumb-item>心理测评管理</el-breadcrumb-item>
    </el-breadcrumb>
    <hr />

    <!-- 头部搜索栏 -->
    <div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="测评题目">
          <el-input
            v-model="formInline.title"
            placeholder="请输入测评题目"
            clearable
            @clear="handleClear1()"
          />
        </el-form-item>
        <el-form-item label="内容简介">
          <el-input
            v-model="formInline.introduction"
            placeholder="请输入内容简介"
            clearable
            @clear="handleClear2()"
          />
        </el-form-item>

        <el-form-item label="分类">
          <el-select
            v-model="formInline.classifyName"
            placeholder="请选择分类"
            clearable
            @clear="handleClear3()"
          >
            <el-option
              v-for="option in nameList"
              :key="option.id"
              :label="option.classifyName"
              :value="option.classifyName"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getData">搜索</el-button>
          <el-button type="success" @click="dialogAddVisible = true">新增测评</el-button>
          <el-button type="danger" @click="delIds()">批量删除</el-button>
        </el-form-item>
      </el-form>

      <!-- 查看弹出框 -->
      <el-dialog v-model="dialogSelVisible" title="查看测评详情" width="730px">
        <el-form :model="selform" label-width="100px">
          <el-form-item label="测评题目" :label-width="formLabelWidth">
            <el-input v-model="selform.title" readonly style="width: 90%" />
          </el-form-item>
          <el-form-item label="内容简介" :label-width="formLabelWidth">
            <el-input v-model="selform.introduction" readonly style="width: 90%" />
          </el-form-item>
          <el-form-item label="分类" :label-width="formLabelWidth">
            <el-input
              v-model="selform.psychologyTestClassify.classifyName"
              readonly
              style="width: 90%"
            />
          </el-form-item>
          <el-form-item label="测评封面图" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              name="file"
            >
              <img v-if="selform.url" :src="selform.url" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="关于测评" :label-width="formLabelWidth">
            <el-input v-model="selform.aboutTest" readonly style="width: 90%" />
          </el-form-item>
          <el-form-item label="你将会获得" :label-width="formLabelWidth">
            <el-input v-model="selform.obtain" readonly style="width: 90%" />
          </el-form-item>
          <el-form-item label="谁适合测试" :label-width="formLabelWidth">
            <el-input v-model="selform.suitable" readonly style="width: 90%" />
          </el-form-item>

          <el-form-item label="参考文献" :label-width="formLabelWidth">
            <el-input v-model="selform.document" readonly style="width: 90%" />
          </el-form-item>
          <el-form-item label="原价" :label-width="formLabelWidth">
            <el-input v-model="selform.beforePrice" readonly style="width: 90%" />
          </el-form-item>
          <el-form-item label="折扣价" :label-width="formLabelWidth">
            <el-input v-model="selform.price" readonly style="width: 90%" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center">
            <el-button type="primary" @click="selNo">关闭</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 新增测评 -->
      <el-dialog v-model="dialogAddVisible" title="新增测评" width="730px">
        <el-form :model="addform" label-width="90">
          <el-form-item label="测评题目" :label-width="formLabelWidth">
            <el-input v-model="addform.title" placeholder="请输入测评题目" style="width: 90%" />
          </el-form-item>
          <el-form-item label="内容简介" :label-width="formLabelWidth">
            <el-input
              v-model="addform.introduction"
              placeholder="请输入内容简介"
              style="width: 90%"
            />
          </el-form-item>
          <el-form-item label="分类" :label-width="formLabelWidth">
            <el-select
              v-model="addform.testClassifyId"
              placeholder="请选择分类"
              clearable
              @clear="handleClear3()"
              style="width: 90%"
            >
              <el-option
                v-for="option in nameList"
                :key="option.testClassifyId"
                :label="option.classifyName"
                :value="option.testClassifyId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="测评封面图" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              name="file"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="关于测评" :label-width="formLabelWidth">
            <el-input v-model="addform.aboutTest" style="width: 90%" />
          </el-form-item>
          <el-form-item label="你将会获得" :label-width="formLabelWidth">
            <el-input v-model="addform.obtain" style="width: 90%" />
          </el-form-item>
          <el-form-item label="谁适合测试" :label-width="formLabelWidth">
            <el-input v-model="addform.suitable" style="width: 90%" />
          </el-form-item>

          <el-form-item label="参考文献" :label-width="formLabelWidth">
            <el-input v-model="addform.document" style="width: 90%" />
          </el-form-item>
          <el-form-item label="原价" :label-width="formLabelWidth">
            <el-input v-model="addform.beforePrice" style="width: 90%" />
          </el-form-item>
          <el-form-item label="折扣价" :label-width="formLabelWidth">
            <el-input v-model="addform.price" style="width: 90%" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center">
            <el-button @click="addNo()">取消</el-button>
            <el-button type="primary" @click="addYes()"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 编辑 -->
      <el-dialog v-model="dialogUpVisible" title="编辑测评" width="730px">
        <el-form :model="upform" label-width="100px">
          <el-form-item label="测评题目" :label-width="formLabelWidth">
            <el-input v-model="upform.title" placeholder="请输入测评题目" />
          </el-form-item>
          <el-form-item label="内容简介" :label-width="formLabelWidth">
            <el-input v-model="upform.introduction" placeholder="请输入内容简介" />
          </el-form-item>
          <el-form-item label="分类" :label-width="formLabelWidth">
            <el-select
              v-model="upform.testClassifyId"
              placeholder="请选择分类"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="option in nameList"
                :key="option.testClassifyId"
                :label="option.classifyName"
                :value="option.testClassifyId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="测评封面图" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              name="file"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="关于测评" :label-width="formLabelWidth">
            <el-input v-model="upform.aboutTest" style="width: 100%" />
          </el-form-item>
          <el-form-item label="你将会获得" :label-width="formLabelWidth">
            <el-input v-model="upform.obtain" style="width: 100%" />
          </el-form-item>
          <el-form-item label="谁适合测试" :label-width="formLabelWidth">
            <el-input v-model="upform.suitable" style="width: 100%" />
          </el-form-item>
          <el-form-item label="参考文献" :label-width="formLabelWidth">
            <el-input v-model="upform.document" style="width: 100%" />
          </el-form-item>
          <el-form-item label="原价" :label-width="formLabelWidth">
            <el-input v-model="upform.beforePrice" style="width: 100%" />
          </el-form-item>
          <el-form-item label="折扣价" :label-width="formLabelWidth">
            <el-input v-model="upform.price" style="width: 100%" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center">
            <el-button @click="upNo()">取消</el-button>
            <el-button type="primary" @click="upYes()"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 表格数据展示 -->
    <div>
      <el-table
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        style="width: 95%; margin-left: 30px"
      >
        <el-table-column :selectable="selectable" type="selection" width="55" />
        <el-table-column label="ID" width="120">
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column property="title" label="测评题目" />
        <el-table-column property="introduction" label="内容简介" />
        <el-table-column property="psychologyTestClassify.classifyName" label="分类" />
        <el-table-column property="url" label="封面图">
          <template #default="scope">
            <el-image
              v-if="scope.row.url"
              :src="scope.row.url"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" >
          <template #default="scope">
            <el-button type="warning" @click="selYes(scope.row)"> 查看 </el-button>
            <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页设置 -->
    <div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import http from '@/util/http'

// 设置表单元素接收数据
const formInline = reactive({
  title: '',
  introduction: '',
  classifyName: '',
})

// 修改初始定义（如果需要）
const nameList = reactive([{}])
// 设置表格接收数据
const tableData = reactive([{}])

// 页面挂载后加载数据
onMounted(() => {
  getData(), getClass()
})

// 清除输入框自动搜索
const handleClear1 = () => {
  formInline.evaluationName = ''
  getData()
}
const handleClear2 = () => {
  formInline.evaluationIntro = ''
  getData()
}
const handleClear3 = () => {
  formInline.classifyName = ''
  getData()
}

//查看弹出框初始化
const dialogUpVisible = ref(false)
const dialogAddVisible = ref(false)
const dialogSelVisible = ref(false)

// 弹出框初始化
const selform = reactive({})
const addform = reactive({
  testClassifyId: null,
})
const upform = reactive({})
const imageUrl = ref('') // 用于预览的图片URL
const tempFile = ref(null) // 临时存储上传的文件对象
const originalUrl = ref('') // 存储原始图片路径
const handleFileChange = (file) => {
  if (file) {
    tempFile.value = file.raw // 存储原始文件对象
    // 创建临时URL用于预览
    imageUrl.value = URL.createObjectURL(file.raw)
  }
}
// 重置表单数据
const resetForm = () => {
  imageUrl.value = ''
  tempFile.value = null
  originalUrl.value = ''
  addform.testClassifyId = null
  addform.title = ''
  addform.introduction = ''
  addform.suitable = ''
  addform.document = ''
  addform.beforePrice = ''
  addform.price = ''
  addform.url = ''
  addform.obtain = ''
  addform.aboutTest = ''
}
//查看方法
const selYes = async (row) => {
  console.log(row)
  try {
    const resp = await axios.get(`psychologyTest/findByIdDuo/${row.id}`)
    console.log(resp)
    if (resp.code === 200) {
      Object.assign(selform, resp.data)
      dialogSelVisible.value = true
    } else {
      ElMessage.error(resp.message)
    }
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取数据失败')
  }
}
const selNo = () => {
  resetForm()
  dialogSelVisible.value = false
}
// 表格宽度
const formLabelWidth = '140px'

const addNo = () => {
  dialogAddVisible.value = false
  resetForm()
  ElMessage('取消添加')
}
const addYes = async () => {
  console.log('开始上传文件', tempFile.value) // 调试文件对象
  if (tempFile.value) {
    const formData = new FormData()
    formData.append('file', tempFile.value)
    const uploadRes = await http({
      url: 'upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    addform.url = uploadRes.data //编译上传数据库的路径
  } else {
    addform.url = originalUrl.value
  }
  // 提交表单数据
  await http.post('psychologyTest/add', {
    testClassifyId: addform.testClassifyId,
    ...addform,
  })
  console.log(addform)
  ElMessage.success('新增成功')
  resetForm() //重置弹框
  getData() //获取全部数据
  dialogAddVisible.value = false
}

// 编辑
const handleEdit = async (index, row) => {
  await http.get(`psychologyTest/findById/${row.id}`).then((resp) => {
    console.log(resp)
    Object.assign(upform, resp.data) // 填充表单数据
    // 设置分类ID
    upform.testClassifyId = resp.data.testClassifyId
    originalUrl.value = upform.url // 保存原始头像路径
    imageUrl.value = originalUrl.value // 初始化预览图片
    dialogUpVisible.value = true // 打开对话框
  })
}
const upNo = () => {
  dialogUpVisible.value = false
  ElMessage('取消编辑')
  upform = {}
  imageUrl.value = originalUrl.value
  tempFile.value = null
}
const getClassNameById = (id) => {
  const found = nameList.find((item) => item.testclassifyId === id)
  return found ? found.classifyName : '未分类'
}
const upYes = async () => {
  console.log('开始上传文件', tempFile.value) // 调试文件对象
  if (tempFile.value) {
    const formData = new FormData()
    formData.append('file', tempFile.value)
    const uploadRes = await http({
      url: 'upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    upform.url = uploadRes.data //编译上传数据库的路径
  } else {
    upform.url = originalUrl.value //如果没有改变图片，那么就使用原始路径
  }
  //提交编辑
  await http
    .put('psychologyTest/edit', {
      ...upform,
    })
    .then((resp) => {
      if (resp.code == 200) {
        ElMessage({
          message: '修改成功！',
          type: 'success',
        })
        resetForm() //重置弹框
        getData() //获取全部数据
        dialogUpVisible.value = false //关闭对话框
      } else {
        ElMessage.error(resp.message)
      }
    })
    .catch((error) => {
      console.error('Error:', error)
      ElMessage.error('请求失败，请稍后再试')
    })
}
const handleDelete = (index, row) => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete(`psychologyTest/del/${row.id}`)
        .then((resp) => {
          if (resp.code == 200) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
          } else {
            ElMessage.error(resp.message)
          }
        })
        .catch((error) => {
          console.error('Error:', error)
          ElMessage.error('请求失败，请稍后再试')
        })
        .finally(() => {
          getData()
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 批量删除
const multipleSelection = ref([])
const ids = ref('')
const delIds = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage('请选择要删除的数据！')
  } else {
    ElMessageBox.confirm('此操作将永久删除该数据, 是否继续??', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        ids.value = multipleSelection.value.map((row) => row.id).join(',')
        console.log(ids.value)
        axios
          .delete(`psychologyTest/delBatch?ids=${ids.value}`)
          .then((resp) => {
            console.log(resp)
            if (resp.code == 200) {
              ElMessage({
                type: 'success',
                message: resp.message,
              })
            } else {
              ElMessage.error(resp.message)
            }
          })
          .catch((error) => {
            console.error('Error:', error)
            ElMessage.error('请求失败，请稍后再试')
          })
          .finally(() => {
            getData()
          })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  }
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 设置分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value = val
  getData()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value = val
  getData()
}

// 获取axios对象实例发送请求
const axios = getCurrentInstance().appContext.config.globalProperties.axios
// 获取表单数据
const getData = () => {
  axios
    .get(
      `psychologyTest/findByCondition?pageNum=${currentPage.value}&pageSize=${pageSize.value}&title=${formInline.title}&introduction=${formInline.introduction}&psychologyTestClassify.classifyName=${formInline.classifyName}`
    )
    .then((resp) => {
      total.value = resp.data.total
      console.log(resp.data)
      tableData.splice(0, tableData.length, ...resp.data.list)
    })
}
// 获取分类数据
const getClass = () => {
  axios.get('TestClassify/findAllName').then((resp) => {
    console.log(resp.data)
    nameList.splice(0, nameList.length, ...resp.data)
  })
}
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 图片显示 */
.block {
  /* border: 1px solid #ccc; */
  width: 100px;
  height: 100px;
  background-color: rgb(245, 247, 250);
  text-align: center;
  line-height: 100px;
}

/* 文件上传 */
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
  border-radius: 5px;
  margin-right: 5px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  background-color: rgb(251, 253, 255);
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
  border: 1px dashed rgb(192, 204, 218);
  border-radius: 5px;
}
</style>